package com.ruoyi.app.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.app.domain.AppAddress;
import com.ruoyi.app.domain.bo.AppAddressBo;
import com.ruoyi.app.domain.vo.AppAddressVo;
import com.ruoyi.app.mapper.AppAddressMapper;
import com.ruoyi.app.service.IAppAddressService;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.EntityCopyUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.redis.RedisUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * APP用户地址信息Service业务层处理
 *
 * @author heike
 * @date 2025-12-21
 */
@RequiredArgsConstructor
@Service
public class AppAddressServiceImpl implements IAppAddressService {

    private final AppAddressMapper baseMapper;

    /**
     * 查询APP用户地址信息
     */
    @Override
    public AppAddressVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询APP用户地址信息列表
     */
    @Override
    public TableDataInfo<AppAddressVo> queryPageList(AppAddressBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AppAddress> lqw = buildQueryWrapper(bo);
        Page<AppAddressVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询APP用户地址信息列表
     */
    @Override
    public List<AppAddressVo> queryList(AppAddressBo bo) {
        LambdaQueryWrapper<AppAddress> lqw = buildQueryWrapper(bo);
        lqw.orderByDesc(AppAddress::getCreateTime);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<AppAddress> buildQueryWrapper(AppAddressBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<AppAddress> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, AppAddress::getUserId, bo.getUserId());
        lqw.like(StringUtils.isNotBlank(bo.getNickName()), AppAddress::getNickName, bo.getNickName());
        lqw.eq(StringUtils.isNotBlank(bo.getMobile()), AppAddress::getMobile, bo.getMobile());
        lqw.eq(StringUtils.isNotBlank(bo.getCity()), AppAddress::getCity, bo.getCity());
        lqw.eq(StringUtils.isNotBlank(bo.getCityCode()), AppAddress::getCityCode, bo.getCityCode());
        lqw.eq(StringUtils.isNotBlank(bo.getCityDetails()), AppAddress::getCityDetails, bo.getCityDetails());
        return lqw;
    }

    /**
     * 新增APP用户地址信息
     */
    @Override
    public Boolean insertByBo(AppAddressBo bo) {
        AppAddress add = BeanUtil.toBean(bo, AppAddress.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改APP用户地址信息
     */
    @Override
    public Boolean updateByBo(AppAddressBo bo) {
        AppAddress update = BeanUtil.toBean(bo, AppAddress.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 修改APP用户地址信息
     */
    @Override
    public Boolean updateByVo(AppAddressVo vo) {
        AppAddress update = BeanUtil.toBean(vo, AppAddress.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(AppAddress entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除APP用户地址信息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }


    @Override
    public Object saveOrUpdate(AppAddressBo bo) {
        if (StringUtils.equals(bo.getStatus(), Constants.SUCCESS)) {
            AppAddressVo addressVo = queryUserId(bo.getUserId(), Constants.SUCCESS);
            if (Objects.nonNull(addressVo)) {
                addressVo.setStatus(Constants.FAIL);
                updateByVo(addressVo);
            }
        }
        if (bo.getId() == null) {
            insertByBo(bo);
            return bo;
        } else {
            AppAddressVo addressVo = queryById(bo.getId());
            EntityCopyUtils.copyPropertiesIgnoreNull(bo, addressVo);
            updateByVo(addressVo);
            return addressVo;
        }
    }

    @Override
    public AppAddressVo queryUserId(Long userId, String status) {
        return baseMapper.selectVoOne(new LambdaQueryWrapper<AppAddress>().eq(AppAddress::getUserId, userId).eq(AppAddress::getStatus, status));
    }
}
